package com.ramblingcoder.bc2.server.tool.update.objects;

import java.io.IOException;
import java.net.Socket;

import com.ramblingcoder.bc2.server.tool.update.commands.Parcel;
import com.ramblingcoder.bc2.server.tool.update.commands.SupportingFunctions;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidArguments;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidDuration;
import com.ramblingcoder.bc2.server.tool.update.exceptions.LogInRequired;
import com.ramblingcoder.bc2.server.tool.update.exceptions.TooLongMessage;

public class Admin {
	//Processes-----\
	public static String yell(Socket socket, String message, int seconds, String playergroup) throws IOException, InvalidArguments, TooLongMessage, InvalidDuration, LogInRequired {
		message = removeInvalid(message);
		
		SupportingFunctions.sendCommand(socket.getOutputStream(), new String[]{"admin.yell", message, ""+(seconds * 1000), playergroup});

		Parcel response = SupportingFunctions.getResponse(socket.getInputStream())[0];
			
		if (response.getStatus().equals("OK"))
			return message;
		else if (response.getStatus().equals("InvalidArguments"))
			throw new InvalidArguments();
		else if (response.getStatus().equals("TooLongMessage"))
			throw new TooLongMessage();
		else if (response.getStatus().equals("InvalidDuration"))
			throw new InvalidDuration("Duration set was out of range. (1-60 seconds)");
		else if (response.getStatus().equals("LogInRequired"))
			throw new LogInRequired();
		
		return null;
	}

	public static String say(Socket socket, String message, String playergroup) throws IOException, InvalidArguments, TooLongMessage, LogInRequired {
		message = removeInvalid(message);
		
		SupportingFunctions.sendCommand(socket.getOutputStream(), new String[]{"admin.say", message, playergroup});
		
		Parcel response = SupportingFunctions.getResponse(socket.getInputStream())[0];
		
		if (response.getStatus().equals("OK"))
			return message;
		else if (response.getStatus().equals("InvalidArguments"))
			throw new InvalidArguments();
		else if (response.getStatus().equals("TooLongMessage"))
			throw new TooLongMessage();
		else if (response.getStatus().equals("LogInRequired"))
			throw new LogInRequired();
		
		return null;
	}
	
	private static String removeInvalid(String message) {
        String valid = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
        
        for (int i = 0; i < message.length(); i++){
        	if (valid.indexOf(message.charAt(i)) == -1){
        		message = removeCharAt(message, i);
        		i = -1;
        	}
        }
        
		return message;
	}
	
	private static String removeCharAt(String s, int pos) {
	   return s.substring(0,pos) + s.substring(pos+1);
	}
	//Processes-----\
}
